package view.game2048;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontMetrics;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
/**
 * The Game2048Tile class is an implementation of a tile.
 * 
 * @author Peled Eldan
 * @author Daniel Manor
 */
public class Game2048Tile extends Canvas 
{
	// Data Members //
	private int value;
	private Font font;
	private Game2048ColorFactory colorFactory;
	
	// Tile CTOR //
	public Game2048Tile(Composite parent, int style)
	{
		// Composite Parent CTOR
		super(parent,style);
		
		// Initialize Data Members
		this.value = 0;
		this.colorFactory = new Game2048ColorFactory();
		
		// Set the Text's font
		Font currFont = getFont();
		this.font = new Font(getDisplay(), currFont.getFontData()[0].getName(), 16, SWT.BOLD);
		setFont(this.font);
		
		// Add a paint listener that will draw the tile and the value string in it's center
		addPaintListener(new PaintListener() 
		{	
			@Override
			public void paintControl(PaintEvent e) 
			{
				FontMetrics fontMetrics = e.gc.getFontMetrics();
				int width = fontMetrics.getAverageCharWidth();
				int tileX = getSize().x/2 - (Integer.toString(value)).length() * width/2;
				int tileY = getSize().y/2 - fontMetrics.getHeight()/2 - fontMetrics.getDescent(); 
				
				if (value > Game2048View.EMPTY)
					e.gc.drawString(Integer.toString(value), tileX, tileY);
			}
		});
	}
	
	// Set the value, change colors accordingly, and redraw
	public void setValue(int value)
	{
		this.value = value;
		changeColors();
		redraw();
	}

	// Change the colors according to this.value
	private void changeColors()
	{
		changeBackgroundColor();
		changeTextColor();
	}
	
	// Change the background color according to this.value
	private void changeBackgroundColor() 
	{
		setBackground(this.colorFactory.createColor(this.value));
	}

	// Change the text (foreground) color according to this.value
	private void changeTextColor() 
	{
		setForeground(this.colorFactory.createTextColor(this.value));
	}
}
